<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
const post = ref(null)
const loading = ref(true)
const error = ref(null)
const currentUser = ref(null)
const commentText = ref('')
const replyTo = ref(null)

// 获取当前用户
const getUser = () => {
  const userStr = localStorage.getItem('user')
  return userStr ? JSON.parse(userStr) : null
}

// 获取帖子详情
const fetchPostDetail = () => {
  const postId = route.params.id
  const savedPosts = localStorage.getItem('socialPosts')
  const allPosts = savedPosts ? JSON.parse(savedPosts) : []
  
  const foundPost = allPosts.find(p => p.id === postId)
  
  if (foundPost) {
    post.value = foundPost
  } else {
    error.value = '帖子不存在'
  }
  
  loading.value = false
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 点赞功能
const toggleLike = () => {
  if (!post.value || !currentUser.value) return
  
  const likeIndex = post.value.likes.findIndex(like => like.username === currentUser.value.username)
  
  if (likeIndex === -1) {
    // 点赞
    post.value.likes.push({ username: currentUser.value.username, createdAt: new Date().toISOString() })
  } else {
    // 取消点赞
    post.value.likes.splice(likeIndex, 1)
  }
  
  // 保存到localStorage
  updatePostInStorage()
}

// 发布评论
const submitComment = () => {
  if (!commentText.value.trim() || !currentUser.value || !post.value) return
  
  const newComment = {
    id: Date.now().toString(),
    author: currentUser.value.username,
    content: commentText.value.trim(),
    createdAt: new Date().toISOString(),
    replyTo: replyTo.value
  }
  
  post.value.comments.push(newComment)
  commentText.value = ''
  replyTo.value = null
  
  // 保存到localStorage
  updatePostInStorage()
}

// 回复评论
const replyToComment = (comment) => {
  replyTo.value = comment
  commentText.value = `回复 @${comment.author}：`
  // 自动聚焦到评论输入框
  setTimeout(() => {
    const input = document.querySelector('.comment-input')
    if (input) input.focus()
  }, 100)
}

// 删除评论
const deleteComment = (commentId) => {
  if (!currentUser.value || !post.value) return
  
  const commentIndex = post.value.comments.findIndex(c => c.id === commentId)
  const comment = post.value.comments[commentIndex]
  
  // 只有评论作者才能删除
  if (comment.author !== currentUser.value.username) {
    alert('只有评论作者可以删除评论')
    return
  }
  
  if (confirm('确定要删除这条评论吗？')) {
    post.value.comments.splice(commentIndex, 1)
    updatePostInStorage()
  }
}

// 更新localStorage中的帖子
const updatePostInStorage = () => {
  const savedPosts = localStorage.getItem('socialPosts')
  const allPosts = savedPosts ? JSON.parse(savedPosts) : []
  
  const postIndex = allPosts.findIndex(p => p.id === post.value.id)
  if (postIndex !== -1) {
    allPosts[postIndex] = post.value
    localStorage.setItem('socialPosts', JSON.stringify(allPosts))
  }
}

// 检查是否已点赞
const isLiked = computed(() => {
  if (!post.value || !currentUser.value) return false
  return post.value.likes.some(like => like.username === currentUser.value.username)
})

// 格式化时间
const formatTime = (timeStr) => {
  const date = new Date(timeStr)
  const now = new Date()
  const diffMs = now - date
  const diffSec = Math.floor(diffMs / 1000)
  const diffMin = Math.floor(diffSec / 60)
  const diffHour = Math.floor(diffMin / 60)
  const diffDay = Math.floor(diffHour / 24)
  
  if (diffSec < 60) return '刚刚'
  if (diffMin < 60) return `${diffMin}分钟前`
  if (diffHour < 24) return `${diffHour}小时前`
  if (diffDay < 7) return `${diffDay}天前`
  return date.toLocaleDateString()
}

onMounted(() => {
  currentUser.value = getUser()
  fetchPostDetail()
})
</script>

<template>
  <div class="post-detail-container">
    <!-- 头部导航 -->
    <header class="detail-header">
      <button class="back-btn" @click="goBack">←</button>
      <h1>帖子详情</h1>
      <div class="header-placeholder"></div>
    </header>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <p>{{ error }}</p>
      <button class="back-btn-text" @click="router.push('/social')">返回社区</button>
    </div>

    <!-- 帖子内容 -->
    <div v-else-if="post" class="post-detail">
      <!-- 帖子头部 -->
      <div class="post-header">
        <div class="user-info">
          <div class="avatar">{{ post.author.charAt(0).toUpperCase() }}</div>
          <div class="user-details">
            <div class="username">{{ post.author }}</div>
            <div class="post-time">{{ formatTime(post.createdAt) }}</div>
          </div>
        </div>
      </div>

      <!-- 帖子正文 -->
      <div class="post-content">
        <p class="post-text">{{ post.content }}</p>
        
        <!-- 图片展示 -->
        <div v-if="post.images && post.images.length > 0" class="post-images">
          <div v-for="(image, index) in post.images" :key="index" class="detail-image-container">
            <img :src="image" alt="帖子图片" class="detail-image">
          </div>
        </div>

        <!-- 视频展示 -->
        <div v-if="post.video" class="post-video">
          <video :src="post.video" controls class="detail-video"></video>
        </div>
      </div>

      <!-- 互动按钮 -->
      <div class="post-actions">
        <button 
          class="action-btn like-btn" 
          :class="{ liked: isLiked }"
          @click="toggleLike"
        >
          <span class="like-icon">{{ isLiked ? '❤️' : '🤍' }}</span>
          <span class="action-text">{{ isLiked ? '已点赞' : '点赞' }}</span>
          <span v-if="post.likes.length > 0" class="action-count">({{ post.likes.length }})</span>
        </button>
      </div>

      <!-- 评论区 -->
      <div class="comments-section">
        <h3 class="comments-title">评论 ({{ post.comments.length }})</h3>
        
        <!-- 评论输入框 -->
        <div class="comment-input-area">
          <div class="user-avatar-small">{{ currentUser?.username?.charAt(0).toUpperCase() || '?' }}</div>
          <div class="comment-input-wrapper">
            <input 
              v-model="commentText"
              type="text" 
              placeholder="添加评论..."
              class="comment-input"
              @keyup.enter="submitComment"
            >
            <button 
              class="comment-submit-btn"
              :disabled="!commentText.trim()"
              @click="submitComment"
            >
              发布
            </button>
          </div>
        </div>
        
        <!-- 评论列表 -->
        <div class="comments-list">
          <div 
            v-for="comment in post.comments" 
            :key="comment.id" 
            class="comment-item"
          >
            <div class="comment-avatar">{{ comment.author.charAt(0).toUpperCase() }}</div>
            <div class="comment-content">
              <div class="comment-header">
                <span class="comment-author">{{ comment.author }}</span>
                <span class="comment-time">{{ formatTime(comment.createdAt) }}</span>
              </div>
              
              <div class="comment-text">
                <span v-if="comment.replyTo" class="reply-info">
                  回复 @{{ comment.replyTo.author }}：
                </span>
                {{ comment.content }}
              </div>
              
              <div class="comment-actions">
                <button 
                  class="reply-btn"
                  @click="replyToComment(comment)"
                >
                  回复
                </button>
                <button 
                  v-if="comment.author === currentUser?.username"
                  class="delete-btn"
                  @click="deleteComment(comment.id)"
                >
                  删除
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.post-detail-container {
  max-width: 100%;
  margin: 0 auto;
  background-color: #fafafa;
  min-height: 100vh;
}

.detail-header {
  position: sticky;
  top: 0;
  background-color: white;
  padding: 16px 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.back-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  padding: 4px 12px;
  border-radius: 4px;
}

.back-btn:hover {
  background-color: #f0f0f0;
}

.detail-header h1 {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.header-placeholder {
  width: 40px;
}

.loading-container, .error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #666;
}

.loading-spinner {
  width: 30px;
  height: 30px;
  border: 3px solid #f0f0f0;
  border-top: 3px solid #ff0000;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.back-btn-text {
  margin-top: 16px;
  padding: 8px 16px;
  background-color: #ff0000;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.post-detail {
  background-color: white;
  max-width: 800px;
  margin: 0 auto;
}

.post-header {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #ff6b6b;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 600;
  font-size: 20px;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.username {
  font-weight: 600;
  color: #333;
  font-size: 16px;
}

.post-time {
  font-size: 12px;
  color: #999;
}

.post-content {
  padding: 16px;
}

.post-text {
  font-size: 16px;
  line-height: 1.6;
  color: #333;
  margin-bottom: 16px;
  word-break: break-word;
}

.post-images {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-image-container {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
}

.detail-image {
  width: 100%;
  height: auto;
  object-fit: cover;
}

.post-video {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 16px;
}

.detail-video {
  width: 100%;
  height: auto;
}

.post-actions {
  padding: 16px;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  background: none;
  border: none;
  cursor: pointer;
  padding: 8px 0;
  color: #666;
  font-size: 16px;
  transition: color 0.2s;
}

.action-btn:hover {
  color: #ff0000;
}

.like-btn.liked {
  color: #ff0000;
}

.like-icon {
  font-size: 24px;
}

.comments-section {
  padding: 16px;
}

.comments-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 16px;
  color: #333;
}

.comment-input-area {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.user-avatar-small {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #ff6b6b;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 600;
  font-size: 14px;
}

.comment-input-wrapper {
  flex: 1;
  display: flex;
  gap: 8px;
}

.comment-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 20px;
  font-size: 14px;
  outline: none;
}

.comment-input:focus {
  border-color: #ff0000;
}

.comment-submit-btn {
  padding: 8px 16px;
  background-color: #ff0000;
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.comment-submit-btn:hover:not(:disabled) {
  background-color: #e60000;
}

.comment-submit-btn:disabled {
  background-color: #ff9999;
  cursor: not-allowed;
}

.comments-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.comment-item {
  display: flex;
  gap: 12px;
}

.comment-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #ff6b6b;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 600;
  font-size: 14px;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.comment-author {
  font-weight: 600;
  font-size: 14px;
  color: #333;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-text {
  font-size: 14px;
  line-height: 1.5;
  color: #333;
  margin-bottom: 6px;
  word-break: break-word;
}

.reply-info {
  color: #666;
}

.comment-actions {
  display: flex;
  gap: 16px;
}

.reply-btn, .delete-btn {
  background: none;
  border: none;
  color: #999;
  font-size: 12px;
  cursor: pointer;
  padding: 4px 0;
}

.reply-btn:hover {
  color: #666;
}

.delete-btn:hover {
  color: #ff0000;
}

@media (max-width: 768px) {
  .detail-header {
    padding: 12px 16px;
  }
  
  .post-detail {
    padding: 12px;
  }
}
</style>